/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import dto.BlockCondition;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import util.DateUtil;
import util.ReadWriteFile;
import xml.XmlFile5;

/**
 *
 * @author phat10130059
 */
public class Login extends javax.swing.JFrame implements WindowListener {

    /**
     * Creates new form Login
     */
    private String pass;
    private String filePath;
    private Demo demo;
    private boolean sta = false;
    private Properties prop = new Properties();
    private InputStream input = null;
    //======================
    private String JLabel1Login;
    private String JLabel2Login;
    private String ErrorMessageLogin;
    private String BtCancel;
    private final String tmpPath = System.getenv("USERPROFILE") + "\\AppData\\Local\\MyCompany\\temp\\";

    public Login() {

        //check file language
        File fileLang = new File(tmpPath + "lang.phat");

        if (!fileLang.exists() || fileLang.isDirectory()) {
            ReadWriteFile.write(tmpPath + "lang.phat", "po");
        }


        String rLang = ReadWriteFile.read(tmpPath + "lang.phat");
        if (rLang.equals("po")) {
            initLanguage(tmpPath + "lange.properties");
        } else if (rLang.equals("en")) {
            initLanguage(tmpPath + "lange_en.properties");
        }



        initComponents();

        this.addWindowListener(this);

        File tempDir = new File(System.getenv("USERPROFILE"));

        filePath = tempDir.getPath();

        //check file pass
        File file = new File(filePath + File.separator + "p.phat");
        if (!file.exists() || file.isDirectory()) {
            ReadWriteFile.write(filePath + File.separator + "p.phat", "123");
            pass = "123";
        } else {
            pass = ReadWriteFile.read(filePath + File.separator + "p.phat");
        }




        setSize(300, 170);
        setResizable(false);
        this.setIconImage(new javax.swing.ImageIcon(getClass().getResource("/img/icon.png")).getImage());

        //check allow run app
//        boolean checkDate = DateUtil.checkDate();
//        if (!checkDate) {
//            System.exit(0);
//
//        }


        //check status when startup app
        File status = new File(filePath + File.separator + "status.phat");
        this.setVisible(true);

        if (status.exists()) {
            String read = ReadWriteFile.read(filePath + File.separator + "status.phat");

            if (read.equals("1")) {
                sta = true;
                btCancel.setEnabled(false);

                if (checkStartWithWindow()) {
                    demo = new Demo(this);
                }

            } else {
                sta = false;
                btCancel.setEnabled(true);
            }

        } else {
            sta = false;
            btCancel.setEnabled(true);
        }


        //check file check in tab1
        File fXmlFile = new File(
                System.getenv("USERPROFILE") + "\\AppData\\Local\\MyCompany\\temp"
                + File.separator + "fileStartWithWindow.xml");
        if (!fXmlFile.exists()) {
            XmlFile5.createXmlNew(
                    System.getenv("USERPROFILE") + "\\AppData\\Local\\MyCompany\\temp"
                    + File.separator + "fileStartWithWindow.xml", new BlockCondition("true"));
        }


        setLocationRelativeTo(null);

    }

    private void initLanguage(String file) {
        try {
            input = new FileInputStream(file);
            Reader reader = new InputStreamReader(input, "UTF-8");
            // load a properties file
            prop.load(reader);

            JLabel1Login = prop.getProperty("JLabel1Login");
            JLabel2Login = prop.getProperty("JLabel2Login");
            ErrorMessageLogin = prop.getProperty("ErrorMessageLogin");
            BtCancel = prop.getProperty("BtCancel");
            reader.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    private boolean checkStartWithWindow() {

        String readFileXml = XmlFile5.readFileXml(
                System.getenv("USERPROFILE") + "\\AppData\\Local\\MyCompany\\temp"
                + File.separator + "fileStartWithWindow.xml");
        System.out.println("xml : " + readFileXml);
        if (!readFileXml.equals("")) {

            if (readFileXml.equals("true")) {
                return true;
            } else if (readFileXml.equals("false")) {
                return false;
            }
        } else {
            return false;
        }

        return false;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtPassword = new javax.swing.JPasswordField();
        jPanel3 = new javax.swing.JPanel();
        btOk = new javax.swing.JButton();
        btCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Login GUARDIÃO EXCLUSIVO");
        addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                formKeyPressed(evt);
            }
        });

        jPanel1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jPanel1KeyPressed(evt);
            }
        });
        jPanel1.setLayout(new java.awt.GridLayout(3, 1));

        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText(JLabel1Login);
        jPanel1.add(jLabel1);

        jPanel2.setLayout(new java.awt.GridLayout(2, 0, 10, 5));

        jLabel2.setText(JLabel2Login);
        jPanel2.add(jLabel2);

        txtPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtPasswordKeyPressed(evt);
            }
        });
        jPanel2.add(txtPassword);

        jPanel1.add(jPanel2);

        btOk.setText("Ok");
        btOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btOkActionPerformed(evt);
            }
        });

        btCancel.setText(BtCancel);
        btCancel.setEnabled(false);
        btCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(94, Short.MAX_VALUE)
                .addComponent(btOk, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btCancel)
                .addGap(16, 16, 16))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(26, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btOk)
                    .addComponent(btCancel))
                .addContainerGap())
        );

        jPanel1.add(jPanel3);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void login() {
        String password = String.valueOf(txtPassword.getPassword());
        if (password.trim().equals(pass)) {

            ReadWriteFile.write(filePath + File.separator + "status.phat", "1");

            this.setVisible(false);

            if (sta) {
                if (demo == null) {
                    demo = new Demo(this);
                }
                demo.setVisible(true);
            } else {
                demo = new Demo(this);
                demo.setVisible(true);

                btCancel.setEnabled(false);
                sta = true;
            }


        } else {
            JOptionPane.showMessageDialog(this, ErrorMessageLogin, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void btOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btOkActionPerformed

        login();
    }//GEN-LAST:event_btOkActionPerformed

    private void btCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelActionPerformed

//        System.exit(0);

    }//GEN-LAST:event_btCancelActionPerformed

    private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed

        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            if (!sta) {
                System.exit(0);
            }

        }

    }//GEN-LAST:event_formKeyPressed

    private void jPanel1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPanel1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            if (!sta) {
                System.exit(0);
            }

        }
    }//GEN-LAST:event_jPanel1KeyPressed

    private void txtPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPasswordKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
            if (!sta) {
                System.exit(0);
            }
        } else if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            login();
        }
    }//GEN-LAST:event_txtPasswordKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Login login = new Login();
                login.setLocationRelativeTo(null);
//                login.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancel;
    private javax.swing.JButton btOk;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    public javax.swing.JPasswordField txtPassword;
    // End of variables declaration//GEN-END:variables

    @Override
    public void windowOpened(WindowEvent e) {
    }

    @Override
    public void windowClosing(WindowEvent e) {
        //        this.setVisible(true);
    }

    @Override
    public void windowClosed(WindowEvent e) {
    }

    @Override
    public void windowIconified(WindowEvent e) {
    }

    @Override
    public void windowDeiconified(WindowEvent e) {
    }

    @Override
    public void windowActivated(WindowEvent e) {
    }

    @Override
    public void windowDeactivated(WindowEvent e) {
    }
}
